#include "videocontext.h"

VideoContext::VideoContext()
{
	m_nWidth = 0;
	m_nHeight = 0;
	m_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	m_vCaptureRunning = true;
	m_vEncodeRunning = true;
}

VideoContext::~VideoContext()
{
	AutoLock al(m_lock);
	AVFrame* p = NULL;
	while (!m_queue.empty())
	{
		p = m_queue.front();
		m_queue.pop();
		SAFE_FREE_AVFRAME(p);
	}
}

void VideoContext::PushFrame(AVFrame* pFrame)
{
	AutoLock al(m_lock);
	m_queue.push(pFrame);
}

AVFrame* VideoContext::PullFrame()
{
	AutoLock al(m_lock);
	if (m_queue.empty())
		return NULL;
	AVFrame* p = m_queue.front();
	m_queue.pop();

	return p;
}

UINT VideoContext::GetSize()
{
	AutoLock al(m_lock);
	return m_queue.size();
}

VideoContext* g_vcapture_ctx = new VideoContext;
mutex ctx_delete_mutex;

bool SetOK()
{
	if (!g_vcapture_ctx->m_event)
		return false;

	return WaitForSingleObject(g_vcapture_ctx->m_event, 0) == WAIT_OBJECT_0;
}

UINT GetVFrameSize()
{
	return g_vcapture_ctx->GetSize();
}

void PushAVFrame(AVFrame* pFrame)
{
	AutoLock al(ctx_delete_mutex);
	if (pFrame && g_vcapture_ctx)
	{
		g_vcapture_ctx->PushFrame(pFrame);
	}
}

AVFrame* PullAVFrame()
{
	return g_vcapture_ctx->PullFrame();
}

void SetCtxValue(int width, int height)
{
	g_vcapture_ctx->m_nWidth = width;
	g_vcapture_ctx->m_nHeight = height;
	SetEvent(g_vcapture_ctx->m_event);
}

void GetCtxValue(int& width, int& height)
{
	width = g_vcapture_ctx->m_nWidth;
	height = g_vcapture_ctx->m_nHeight;
}